<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      margin: 0 auto;
      background-color: #f5f5f5;
    }

    .box {
      width: 1200px;
      display: flex;
      flex-wrap: wrap;
      margin: 0 auto;
      /* justify-content: space-between; */
    }

    .product {
      width: 170px;
      padding: 10px;
      background-color: #fff;
      margin-right: 12px;
      margin-bottom: 10px;
    }

    .product:nth-child(6n) {
      margin-right: 0;
    }

    .auto-img {
      width: 100%;
      display: block;
    }
  </style>
</head>

<body>

  <div class="box">


  </div>


  <script>

    window.onload = function () {

      var productData = [

      ];

      for (var i = 1; i <= 100; i++) {
        productData.push({
          name: '三只松鼠开口松子100g休闲零食每日坚果干果坚果炒货东北手剥红松子 100g',
          price: i,
          img: 'https://img14.360buyimg.com/jdcms/s150x150_jfs/t1/152630/37/30252/125609/6337193aEddcc2082/c892d645864cfc2f.jpg.avif'
        })
      };

      console.log('productData ==> ', productData);

      //取30个商品
      var offset = 0;

      //每次触底加载12个商品
      var count = 12;

      //初始获取商品数据量
      var initCount = 30;

      var initProductData = productData.slice(offset, offset + initCount);
      offset += initCount;
      console.log('initProductData ==> ', initProductData);

      //创建商品数据
      function createProduct(proData) {

        //proData: 商品数据, array, [{}, {}, ..]
        var box = document.querySelector('.box');
        proData.forEach(function (item) {
          var div = document.createElement('div');
          div.classList.add('product');
          div.innerHTML = `<div>
            <img class="auto-img" src="${item.img}" alt="">
          </div>
          <div>${item.name}</div>
          <div>${item.price}</div>`;
          box.appendChild(div);
        })
      }
      createProduct(initProductData);

      //函数节流: 在一定时间内, 只触发一次

      var isYes = true;

      document.onscroll = function () {
        var cat = document.documentElement.scrollHeight - document.documentElement.clientHeight -
          document.documentElement.scrollTop;
        if (cat <= 100) {
          if (offset > productData.length) return;
          console.log(offset);
          var initProductData = productData.slice(offset, offset + count > productData.length ? productData.length : offset + count);
          offset += count;
          createProduct(initProductData);
        }
        if (!isYes) {
          return;
        }

        isYes = false;

        setTimeout(function () {

          isYes = true;

          console.log('触发滚动事件');
          //实现你的逻辑

        }, 1000)

      }

    }




  </script>
</body>

</html>